package com.whynot.frame.auth.shiro.interceptor;

import com.whynot.frame.auth.shiro.cache.AuthCache;
import com.whynot.frame.basic.util.RedirectUtil;
import com.whynot.frame.basic.util.SpringUtil;
import com.whynot.frame.basic.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 描述: 并发过滤器，防止一个账号多次登录:
 * 作者: chenyao
 * 日期: 2018-06-30.
 * 项目名称: whynot-boot-shiro-jwt-server
 * 版本: 1.0.0
 * JDK: since 1.8
 */
public class KickoutSessionControlInterceptor extends HandlerInterceptorAdapter {
    AuthCache authCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(StringUtils.isEmpty(authCache)){
            authCache = SpringUtil.getBean(AuthCache.class);
        }

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getParameter("username");
        String token = httpServletRequest.getHeader("Authorization");
        Map<String,Object> bean = authCache.getUser(authorization);
        if(StringUtils.isNotEmpty(bean) && StringUtils.isEmpty(token)){
            //将重复登录请求跳转到 /repeatLogin
            RedirectUtil.toResponse(request, response,"repeatLogin");
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

}